<?php

send_mess("Starting update of database... <br>");

// Clear out the Uploads folder if there is any thing in there.
$target = "../Upload/";
system('rm' . $target . '/*', $rm_sys_return);

// Main parser script
$gen_nbr = 0;
$exp_nbr = 0;
$name_nbr = 0;
$clin_nbr = 0;

send_mess("Removing database tables... <br>");

// Clear the database
system("perl ../Perl/delete_snp.pl", $gen_sys_return_delete);
system("perl ../Perl/delete_exp_data.pl", $exp_sys_return_delete);
//
// Please note that the gene_names_symbols table is cleared by the delete_exp_data.pl
// and that the extract_clin_data.pl handles it's own deleting.
// Check that the delete db scripts execute sucessfully.
if ($gen_sys_return_delete == 0 && $exp_sys_return_delete == 0) {
    // Loop over all input files, upload them and parse the data into the database.
    foreach ($_FILES as $key => $value) {
        // Check if it is a genotype or a expressions file that is uploaded.
        if (preg_match("/gen_upload.*/", $key)) {
            // Upload the file
            $gen_run = upload_file($key, "gen", $gen_nbr);
            if ($gen_run[0] == 1) {
                // Send the data to the db
                data2db($gen_run[1], "gen");
            }
            $gen_nbr++;
        } elseif (preg_match("/exp_upload.*/", $key)) {
            // Upload the file
            $exp_run = upload_file($key, "exp", $exp_nbr);
            if ($exp_run[0] == 1) {
                // The if switch is needed to parse the numbers of the upload files correctly.
                if ($exp_nbr == 0) {
                    // Send the data to the db
                    data2db($exp_run[1], "exp", $_POST['tissue_type']);
                } else {
                    $temp_name = "tissue_type" . $exp_nbr;
                    data2db($exp_run[1], "exp", $_POST[$temp_name]);
                }
            }
            $exp_nbr++;
        } elseif (preg_match("/nameVsSymbol_upload.*/", $key)) {
            $name_run = upload_file($key, "names", $names_nbr);
            if ($name_run[0] == 1) {
                data2db($name_run[1], "name");
            }
            $name_nbr++;
        } elseif (preg_match("/clinical_upload.*/", $key)) {
            $name_run = upload_file($key, "clinical", $clin_nbr);
            if ($name_run[0] == 1) {
                data2db($name_run[1], "clinical");
            }
            $clin_nbr++;
        } else {
            send_mess("FAIL: Error! Could not match" . $key);
            break;
        }
    }
}

$tissue_table_run = setup_tissue_table();
if ($tissue_table_run == TRUE)
    echo "Tissue type table created. <br>";
else
    echo "FAILED: Could not create tissue type table.<br>";

include 'dbclose.php';
send_mess("Finished update of database... <br>");

// ******************************
// Functions used by main script
// ******************************

function data2db($file, $type, $tissue_type) {
    if ($type == "gen") {
        send_mess("Trying to extract genotypes... <br>");

        $sys_return_extract = -1;
        system("perl ../Perl/extract_snp.pl " . $file, $sys_return_extract);

        // Check that the system exits without problems.
        if ($sys_return_extract == 0)
            send_mess("Finished extracting genotypes... <br>");
        else
            send_mess("FAIL: extract_snp.pl failed. <br>");
    }
    elseif ($type == "name") {
        send_mess("Trying to extract gene names vs. symbols... <br>");

        $sys_return_extract = -1;
        system("perl ../Perl/extract_gene_names_symbols.pl " . $file, $sys_return_extract);

        // Check that the system exits without problems.
        if ($sys_return_extract == 0)
            send_mess("Finished extracting names vs. symbols... <br>");
        else
            send_mess("FAIL: extract_gene_names_symbols.pl failed. <br>");
    }
    elseif ($type == "clinical") {
        send_mess("Trying to extract clinical data... <br>");

        $sys_return_extract = -1;
        system("perl ../Perl/extract_clin_data.pl " . $file, $sys_return_extract);

        // Check that the system exits without problems.
        if ($sys_return_extract == 0)
            send_mess("Finished extracting clinical data... <br>");
        else
            send_mess("FAIL: extract_clin_data.pl failed. <br>");
    }
    else {
        send_mess("Trying extracting expression profiles... <br>");

        $sys_return_extract = -1;
        system("perl ../Perl/extract_exp_data.pl " . $file . " " . $tissue_type, $sys_return_extract);

        // Check that the system exits without problems.
        if ($sys_return_extract == 0) {
            send_mess("Finished extracting expression profiles.<br>");
        } else {
            send_mess("FAIL: extract_exp_data.pl.<br>");
        }
    }
}

function upload_file($infile, $type, $nbr) {    
    $target = $target . $type . $nbr;
    $ok = 1;
    if (move_uploaded_file($_FILES[$infile]['tmp_name'], $target)) {

        send_mess("The file " . basename($_FILES[$infile]['name']) . " has been uploaded <br>");
        $return = array(1, $target);
        return $return;
    } else {
        send_mess("FAIL: Sorry, there was a problem uploading your file. <br>");
        $return = array(0, $target);
        return $return;
    }
}

function send_mess($str) {
    echo $str;
    @ob_end_flush();
    flush();
    sleep(1);
}

function setup_tissue_table() {
    include 'dbconf.php';
    include 'dbopen.php';

    $delete = "DELETE FROM tissue_type";
    mysql_query($delete);

    $query = "INSERT INTO tissue_type (name)
              SELECT DISTINCT tissue_type FROM exp_level";
    $result = mysql_query($query);

    include 'dbclose.php';

    return $result;
}
?>
